import json

import unicodedata
from django.http import HttpResponse
from docx import *
from sts.sts import Sts

from Enums import *


# Create your views here.

def parseForm(request):
    if request.method != 'POST':
        return JsonResponseUtf8({}, 405, False, "方法不允许")
    session = request.session.get("info")
    if session is None:
        return JsonResponseUtf8({}, 404, False, "会话过期")
    register = request.FILES.get("registrationForm")
    year = request.POST.get("year")
    if register is None:
        return JsonResponseUtf8({}, 500, False, "文件为空")
    file_name = register.name
    suffix = file_name.split(".")[-1]
    if suffix != "docx" and suffix != "doc":
        return JsonResponseUtf8({}, 500, False, "报名表文件类型错误")
    data = {}
    try:
        document = Document(register)
        if year == "2021":
            data = parse2021(document)
        elif year == "2022":
            data = parse2022(document)
    except Exception as e:
        return JsonResponseUtf8({}, 500, False, str(e))
    data["year"] = year
    data["project"]["type"] = type2track(data["project"]["type"])
    return JsonResponseUtf8(data, 200, True, "操作成功")


def parse2021(document):
    project = {}
    captain = {}
    members = []
    teachers = []
    project_content_brief = ""

    for i in document.paragraphs:
        s = re.search("作品内容简介：", i.text)
        if s is not None:
            project_content_brief = i.text.split("作品内容简介：")[1]
            break
    tb0 = document.tables[0]
    tb2 = document.tables[2]
    t1 = getTableTexts(tb0)
    t2 = getTableTexts(tb2)
    project["name"] = t1[0][1]
    project["type"] = t1[2][1]
    project["college"] = College.modify(t1[4][1])
    project["brief"] = project_content_brief
    captain["name"] = t2[0][2]
    captain["sex"] = t2[0][4]
    captain["phone"] = t2[2][4]
    captain["college"] = College.modify(t2[1][2])
    captain["major"] = t2[1][4]
    captain["sno"] = t2[2][2]
    captain["email"] = t1[6][1]
    captain["qq"] = t1[6][3]
    captain["wechat"] = ""
    t2 = removeBlank(t2)
    members_info = getMembersList(t2, "合作")
    teachers_info = getMembersList(t2, "教师")
    for i in range(len(members_info)):
        if i == 0:
            continue
        m = members_info[i]
        member = {}
        try:
            member["name"] = m[1]
            member["sex"] = m[3]
            member["sno"] = m[2]
            member["college"] = College.modify(m[5])
            member["major"] = m[4]
            member["index"] = i - 1
            member["division"] = ""
            member["email"] = ''
            member["qq"] = ''
            member["phone"] = ''
            member["wechat"] = ''
            if i == 1 and member["name"] == captain["name"]:
                captain["major"] = member["major"]
                captain["college"] = member["college"]
        except IndexError:
            continue
        members.append(member)
    if members[0]["sno"] != captain["sno"]:
        member = {
            "name": captain["name"],
            "sex": captain["sex"],
            "sno": captain["sno"],
            "college": College.modify(captain["college"]),
            "major": captain["major"],
            "index": -1,
            "division": "",
            "email": captain["email"],
            "qq": captain["qq"],
            "phone": captain["phone"],
            "wechat": captain["wechat"],
        }
        members = [member] + members
    if members[0]["sno"] == captain["sno"]:
        # members[0]["name"] = captain["name"]
        # members[0]["sex"] = captain["sex"]
        # members[0]["sno"] = captain["sno"]
        # members[0]["college"] = College.modify(captain["college"])
        # members[0]["major"] = captain["major"]
        members[0] = captain
        members[0]['index'] = 0
        members[0]['division'] = '队长'
    for i in range(len(members)):
        members[i]["index"] = i
    for i in range(len(teachers_info)):
        if i == 0:
            continue
        t = teachers_info[i]
        teacher = {}
        try:
            teacher["name"] = t[1]
            teacher["title"] = t[3]
            teacher["tno"] = t[2]
            teacher["college"] = College.modify(t[6])
            teacher["phone"] = t[5]
            teacher["email"] = ""
            teacher["index"] = i - 1
        except IndexError:
            continue
        teachers.append(teacher)
    return {
        "project": project,
        # "captain": captain,
        "members": members,
        "teachers": teachers
    }


def parse2022(document):
    project = {}
    captain = {}
    members = []
    teachers = []
    raw = {
        "作品名称：": "",
        "负责人：": "",
        "联系电话：": "",
        "指导学院：": "",
        "作品类别：": ""
    }
    for i in document.paragraphs:
        text = i.text.replace(" ", "")
        # s = re.search("作品内容简介：", i.text)
        for k in raw.keys():
            if re.search(k, text) is not None:
                raw[k] = text.split(k)[1]
                break
    project["name"] = raw["作品名称："]
    project["type"] = raw["作品类别："]
    project["college"] = College.modify(raw["指导学院："])
    captain["name"] = raw["负责人："]
    captain["phone"] = raw["联系电话："]

    tb0 = document.tables[0]
    t0 = removeBlank(getTableTexts(tb0))
    captain["sex"] = t0[1][4]
    captain["college"] = College.modify(t0[2][2])
    captain["major"] = t0[2][4]
    captain["sno"] = t0[2][6]
    captain["email"] = t0[3][4]
    captain["qq"] = ""
    captain["wechat"] = t0[3][6]
    members_info = getMembersList(t0, "团队成员")
    teachers_info = getMembersList(t0, "指导老师")
    project_brief = getMembersList(t0, "作品简介")
    for i in range(len(members_info)):
        if i == 0:
            continue
        m = members_info[i]
        member = {}
        try:
            member["name"] = m[2]
            member["sex"] = "未知"
            member["sno"] = m[1]
            member["college"] = College.modify(m[4])
            member["major"] = m[5]
            member["index"] = i - 1
            member["division"] = m[6]
            member["email"] = ''
            member["qq"] = ''
            member["phone"] = m[3]
            member["wechat"] = ''
        except IndexError:
            continue
        members.append(member)
    if members[0]["sno"] != captain["sno"]:
        member = {
            "name": captain["name"],
            "sex": captain["sex"],
            "sno": captain["sno"],
            "college": College.modify(captain["college"]),
            "major": captain["major"],
            "index": -1,
            "division": "队长",
            "email": captain["email"],
            "qq": captain["qq"],
            "phone": captain["phone"],
            "wechat": captain["wechat"],
        }
        members = [member] + members
    if members[0]["sno"] == captain["sno"]:
        # members[0]["name"] = captain["name"]
        # members[0]["sex"] = captain["sex"]
        # members[0]["sno"] = captain["sno"]
        # members[0]["college"] = College.modify(captain["college"])
        # members[0]["major"] = captain["major"]
        members[0] = captain
        members[0]['index'] = 0
        members[0]['division'] = '队长'
    for i in range(len(members)):
        members[i]["index"] = i
    for i in range(len(teachers_info)):
        if i == 0 or i == len(teachers_info) - 1:
            continue
        t = teachers_info[i]
        teacher = {}
        try:
            teacher["name"] = t[1]
            teacher["title"] = t[2]
            teacher["tno"] = t[6]
            teacher["college"] = College.modify(t[3])
            teacher["phone"] = t[4]
            teacher["email"] = t[5]
            teacher["index"] = i - 1
        except IndexError:
            continue
        teachers.append(teacher)
    for i in range(len(teachers)):
        teachers[i]["index"] = i
    project["brief"] = ""
    for i in range(len(project_brief)):
        project["brief"] += project_brief[i][1]
    return {
        "project": project,
        # "captain": captain,
        "members": members,
        "teachers": teachers
    }


def getTexts(row):
    cells = row.cells
    texts = []
    for cell in cells:
        text = cell.text
        text = unicodedata.normalize('NFKC', text)
        # text.replace(" ","")
        text = text.replace("\t", "")
        text = text.replace("\n", "")
        # text = text.replace("\xa6", "")
        texts.append(text)
    texts = duplicateRemove(texts)
    return texts


def getTableTexts(table):
    rows = table.rows
    table_texts = []
    for row in rows:
        table_texts.append(getTexts(row))
    return table_texts


def duplicateRemove(items: list):
    seen = []
    for item in items:
        if item not in seen:
            seen.append(item)
    return seen


def removeBlank(items: List[List[str]]):
    for item in items:
        for x in range(len(item)):
            item[x] = unicodedata.normalize('NFKC', item[x])
            item[x] = item[x].replace("\t", "")
            item[x] = item[x].replace("\n", "")
            item[x] = item[x].replace(" ", "")
            # item[x] = item[x].replace("\xa6", "")
    return items


def getMembersList(items: List[List[str]], pattern: str) -> List[List[str]]:
    rtn = []
    for item in items:
        s = item[0]
        if re.search(pattern, s) is not None:
            rtn.append(item)
    return rtn


def get_credential_demo():
    config = {
        # 请求URL，域名部分必须和domain保持一致
        # 使用外网域名时：https://sts.tencentcloudapi.com/
        # 使用内网域名时：https://sts.internal.tencentcloudapi.com/
        'url': 'https://sts.tencentcloudapi.com/',
        # 域名，非必须，默认为 sts.tencentcloudapi.com
        # 内网域名：sts.internal.tencentcloudapi.com
        'domain': 'sts.tencentcloudapi.com',
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': 'AKIDYw5xYswkHXYHjuoSpvkIZZIkvoRnreAP',
        # 固定密钥
        'secret_key': '1lDOJxKPDn67rLYU8WdT2JK4YppZ2EAp',
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        'bucket': 'sanhangbei-1257646261',
        # 换成 bucket 所在地区
        'region': 'ap-chengdu',
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': ['exampleobject', 'exampleobject2'],
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
        ],
        # 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
        "condition": {
            "ip_equal": {
                "qcs:ip": [
                    "127.0.0.1",
                ]
            }
        }
    }

    sts = Sts(config)
    response = sts.get_credential()
    return HttpResponse(
        json.dumps(dict(response)),
        content_type="application/json,charset=utf-8"
    )
    # print('get data : ' + json.dumps(dict(response), indent=4))


def JsonResponseUtf8(data, code: int, success: bool, message: str):
    rtn = {
        "data": data,
        "code": code,
        "success": success,
        "message": message
    }
    return HttpResponse(
        json.dumps(rtn, ensure_ascii=False),
        content_type="application/json,charset=utf-8"
    )
